package cc.jq1024.http;

import cc.jq1024.annotations.DCCValue;
import cc.jq1024.annotations.RateLimiterAccessInterceptor;
import cc.jq1024.domain.service.IDCCService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author li--jiaqiang
 * @date 2024−07−20
 */
@RestController
@CrossOrigin("*")
@RequestMapping("/test")
public class TestController {

    @DCCValue("result:open")
    private String result;

    @Resource
    private IDCCService idccService;

    /**
     * http://localhost:9000/api/v1/test/info
     */
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "150")
    }, fallbackMethod = "hystrixError")
    @RateLimiterAccessInterceptor(key = "id", permitsPerSecond = 3, blacklistCount = 3, fallbackMethod = "rateLimiterError")
    @RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
    public String getUserInfo(@PathVariable("id") String id) {

        if ("open".equals(result)) return result;
        return "close";
    }
    public String rateLimiterError(String id) {
        return "id: " + id + " 限流";
    }
    public String hystrixError(String id) {
        return "id: " + id + "熔断";
    }

    /**
     * http://localhost:9000/api/v1/test/update?key=result&value=close
     */
    @RequestMapping(value = "update", method = RequestMethod.GET)
    public String update(@RequestParam("key") String key, @RequestParam("value") String value) throws Exception {
        idccService.set(key, value);
        return "成功！" + key + ":" + value;
    }
}